package com.controller;

import com.bean.User;
import com.config.jwt.JwtFilter;
import com.service.UserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import java.util.Map;
import java.util.Optional;

import static com.tool.Tool.getJwt;
import static com.tool.Tool.getShaDigest;
import static com.tool.Tool.sendMail;

/**
 * Created by Yuicon on 2017/3/19.
 */
@RestController
@CrossOrigin(origins = {"*"}, methods = {RequestMethod.OPTIONS, RequestMethod.POST, RequestMethod.GET})
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param login 需要登录的用户实例
     * @return jwt
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    String login(@RequestBody User login) {
        String compactJws = "";
        User user = userService.findByPhone(login.getPhone());
        if (user != null) {
            if (user.getPassWord().equals(getShaDigest(login.getPassWord(), "SHA-256"))) {
                compactJws = getJwt(user.getId(), 86400000);
            }
        }
        return compactJws;
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    int register(@RequestBody User register) {
        register.setPassWord(getShaDigest(register.getPassWord(), "SHA-256"));
       return userService.insert(register);
    }

    @RequestMapping(value = "/sendRetrievePasswordMail", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    boolean sendRetrievePasswordMail(String phone) {
        Optional<User> user = Optional.ofNullable(userService.findByPhone(phone));
        if (user.isPresent()) {
            try {
                String token = getJwt(user.get().getPhone(), 720000).replace(".", "_yui_");
                sendMail("max@agideo.com", "max@agideo.com", "wang159753.0.",
                        user.get().getEmail(),
                        "稚互动动",
                        "<a href=\"http://localhost:3000/retrievePassword/" + token +
                                "\" " +
                                "style=\"font-size: 16px;font-weight: 600;color:#377ab9;text-decoration:none;" +
                                "cursor:pointer;" +
                                "white-space:nowrap;overflow: hidden;width: 415px;display: block;" +
                                "text-overflow: ellipsis;\" " +
                                "target=\"_blank\">" +
                                "请点击链接重置密码,两个小时后无效" +
                                "</a>");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return false;
        }
        return true;
    }

    @RequestMapping(value = "/retrievePassword", method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    int retrievePassword(@RequestBody Map map) {
        String token = (String) map.get("token");
        String password = (String) map.get("password");
        token = token.replace("_yui_", ".");
        final Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(JwtFilter.SECRET_KEY).parseClaimsJws(token).getBody();
        } catch (final Exception e) {
            return 0;
        }
        User user = userService.findByPhone(claims.getSubject());
        user.setPassWord(getShaDigest(password, "SHA-256"));
        return userService.update(user);
    }

    @RequestMapping(value = "/secure/currentUser", method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    User currentUser(ServletRequest req) {
        return userService.findOne(req);
    }


}
